import random
import json

from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView

from user import models,userser
from rest_framework.response import Response
from rest_framework import status

from utils.SenMes import send_message
from utils.tooljwt import tooljwt

from utils.authentiction import JWTAuthenticationss

from utils.MyRedis import myredis
class UserRegister(APIView):
    def post(self,request):
        ser=userser.UserSer(data=request.data)
        # 验证数据是否有效，然后调用添加的方法
        if ser.is_valid():
            ser.save()
            # 添加成功
            return Response({"mes":"ok","data":ser.data,"code":status.HTTP_201_CREATED})
        else:
            # 添加失败
            return  Response({"mes":"ok","data":ser.errors,"code":status.HTTP_400_BAD_REQUEST})


class UserLogin(APIView):
    def post(self,request):
        # 获取用户名和密码
        username=request.data.get("username")
        password=request.data.get("password")
        data=models.UserModel.objects.filter(username=username).first()
        if data:
            if data.password==password:
                # 获取用户信息，生成token
                token=tooljwt.gettoken({"id":data.id,"username":data.username})
                # 将token返回给前端
                return Response({"msg":"ok","data":{"id":data.id,"username":data.username,"token":token}})
            else:
                return Response({"msg":"密码错误"})
        else:

            return Response({"msg":"用户名错误"})








class UserCenter(APIView):

    authentication_classes = (JWTAuthenticationss,)
    def get(self,request):

        return Response({"msg":"我是会员中心"})




class SenCode(APIView):
    #获取前端遗传的手机号
    def post(self,request):
        phone=request.data.get('phone')
        # 生成随机验证码
        code=str(random.randint(1000,9999))
        res=json.loads(send_message(phone,code,2))
        #将验证码保存到redis中
        if res["statusCode"]=="000000":
            #将验证码保存到redis中
            myredis.set_time_str(phone,60*2,code)
            return Response({"msg":"发送验证码"})
        else:
            return Response({"msg":res['statusMsg']})

class Login(APIView):
    def post(self,request):
        phone=request.data.get("phone")
        code=request.data.get("code")
#         验证手机是否正确
        data=models.UserModel.objects.filter(phone=phone).first()
        if data:
        #     如果手机号正确在从redis读取正确的验证码
            rediscode=myredis.get_str(phone)
            if code==rediscode:
                return Response({"msg":"登录成功","data":{}})
            else:
                return Response({"msg":"验证码不正确"})
        else:
            return Response({"msg":"手机号不正确"})


















